package com.csaba.db.views;

import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.csaba.db.Activator;
import com.csaba.db.actions.CloseUserAction;
import com.csaba.db.actions.OpenUserAction;

/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class UserDBExplorer extends ViewPart
{
	private TreeViewer viewer;
	private DrillDownAdapter drillDownAdapter;
	private Action refreshAction;
	private Action openAction;
	private Action closeAction;
	private Action doubleClickAction;

	class NameSorter extends ViewerSorter
	{
	}

	/**
	 * The constructor.
	 */
	public UserDBExplorer()
	{
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	@Override
	public void createPartControl( final Composite parent )
	{
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		viewer.setContentProvider(new UserDBContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		viewer.setInput(getViewSite());

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "com.csaba.db.viewer");
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();

		//XXX is this the right place?
		final IResourceChangeListener refresher = new IResourceChangeListener()
		{

			@Override
			public void resourceChanged( final IResourceChangeEvent arg0 )
			{
				refresh();
			}
		};

		ResourcesPlugin.getWorkspace().addResourceChangeListener(refresher);

		viewer.addSelectionChangedListener(new ISelectionChangedListener()
		{

			@Override
			public void selectionChanged( final SelectionChangedEvent event )
			{
				boolean enabled = false;
				final ISelection select = event.getSelection();
				if ( select instanceof IStructuredSelection )
					if ( ( (IStructuredSelection) select ).size() == 1 )
						if ( ( (IStructuredSelection) select ).getFirstElement() instanceof UserDB )
							if ( !( (UserDB) ( (IStructuredSelection) select ).getFirstElement() ).isOpen() )
								enabled = true;
				openAction.setEnabled(enabled);

			}
		});
	}

	private void hookContextMenu()
	{
		final MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener()
		{
			public void menuAboutToShow( final IMenuManager manager )
			{
				UserDBExplorer.this.fillContextMenu(manager);
			}
		});
		final Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars()
	{
		final IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown( final IMenuManager manager )
	{
		manager.add(refreshAction);
		manager.add(new Separator());
		manager.add(closeAction);
	}

	private void fillContextMenu( final IMenuManager manager )
	{
		manager.add(refreshAction);
		manager.add(openAction);
		manager.add(closeAction);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar( final IToolBarManager manager )
	{
		manager.add(refreshAction);
		manager.add(closeAction);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void refresh()
	{
		( (UserDBContentProvider) viewer.getContentProvider() ).refresh();
		viewer.refresh();
	}

	private void makeActions()
	{
		refreshAction = new Action()
		{
			@Override
			public void run()
			{
				refresh();
			}
		};
		refreshAction.setText("Frissít");
		refreshAction.setToolTipText("Frissítsd az adatbázisok tartalmát");
		refreshAction.setImageDescriptor(Activator.getDefault().getImageDescriptor(Activator.IMG_REFRESH));

		closeAction = new Action()
		{
			@Override
			public void run()
			{
				final CloseUserAction action = new CloseUserAction();
				action.init(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
				action.run(this);
			}
		};
		closeAction.setText("Bezárás");
		closeAction.setToolTipText("Az aktív project bezárása.");
		closeAction.setImageDescriptor(Activator.getDefault().getImageDescriptor(Activator.IMG_CLOSE));

		openAction = new Action()
		{
			@Override
			public void run()
			{
				final ISelection selection = viewer.getSelection();
				final Object obj = ( (IStructuredSelection) selection ).getFirstElement();
				if ( obj instanceof UserDB )
				{
					final OpenUserAction action = new OpenUserAction(( (UserDB) obj ).getName());
					action.init(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
					action.run(this);
				}
				else
				{
					showMessage("A megnyitás művelet nem értelmezett ezen az objektumon: " + obj);
				}
			}
		};
		openAction.setText("Megnyit");
		openAction.setToolTipText("A kiválasztott adatbázis megnyitása (az aktív bezáródik majd).");
		openAction.setImageDescriptor(Activator.getDefault().getImageDescriptor(Activator.IMG_OPEN));

		doubleClickAction = new Action()
		{
			@Override
			public void run()
			{
				final ISelection selection = viewer.getSelection();
				final Object obj = ( (IStructuredSelection) selection ).getFirstElement();
				showMessage("Double-click detected on " + obj.toString());
			}
		};
	}

	private void hookDoubleClickAction()
	{
		viewer.addDoubleClickListener(new IDoubleClickListener()
		{
			public void doubleClick( final DoubleClickEvent event )
			{
				doubleClickAction.run();
			}
		});
	}

	private void showMessage( final String message )
	{
		MessageDialog.openInformation(viewer.getControl().getShell(), "UserDBExplorerAction", message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	@Override
	public void setFocus()
	{
		viewer.getControl().setFocus();
	}
}